package net.jxvtc.blogv1.controller;

import net.jxvtc.blogv1.domain.Authority;
import net.jxvtc.blogv1.domain.User;
import net.jxvtc.blogv1.service.AuthorityService;
import net.jxvtc.blogv1.service.UserService;
import net.jxvtc.blogv1.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: blogv1
 * @description: 用户控制器
 * @author: 蓝建平
 * @create: 2020-10-24 10:52
 **/
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AuthorityService authorityService;

    /**
     * 功能：按用户名，进行分页模糊查询
     * @param async  是否异步，默认不是异步，即false, 如果异步，则采用ajax方式加载数据
     * @param pageIndex  第几页，默认为第0页
     * @param pageSize   每页几条记录，默认为每页10条
     * @param name      查询的关键字  （用户名） 如：用户名为 张，则 LIKE '%张%'
     * @param model    通过model向页面传递数据。
     * @return   ModelAndView
     *          包括模型和视图，视图指定要跳转的页面或把数据加载到页面的某个部分
     *                       模型表示向页面传递的数据
     */
    @GetMapping
    public ModelAndView list(@RequestParam(value = "async", required = false) boolean async,
                             @RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize,
                             @RequestParam(value = "name", required = false, defaultValue = "") String name, Model model) {

        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        Page<User> page = userService.listUsersByNameLike(name, pageable);
        List<User> list = page.getContent(); // 当前所在页面数据列表
        for (User user : list) {
            System.out.println(user.getName());
        }
        model.addAttribute("page", page);
        model.addAttribute("userList", list);
        return new ModelAndView(async == true ? "users/list :: #mainContainerRepleace" : "users/list", "userModel",
                model);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Response> delete(@PathVariable("id") Long id) {
        try
        {
            userService.removeUser(id);
        }catch (Exception ex)
        {
            return ResponseEntity.ok().body(new Response(false,ex.getMessage()));
        }
        return ResponseEntity.ok().body(new Response(true,"删除成功！"));

    }

    /**
     * 获取创建表单页面
     * @param model
     * @return
     */
    @GetMapping("/add")
    public ModelAndView createForm(Model model) {
        model.addAttribute("user", new User(null,null,null,null));
        return new ModelAndView("users/add", "userModel", model);
    }


    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    /**
     * 保存或者修改用户
     *
     * @param user
     * @return
     */
    @PostMapping
    public ResponseEntity<Response> save(User user, Long authorityId) {
        List<Authority> authorities = new ArrayList<>();
        authorities.add(authorityService.getAuthorityById(authorityId).get());
        user.setAuthorities(authorities);
        try {


            userService.saveOrUpateUser(user);
        } catch (Exception e) {
            return ResponseEntity.ok().body(new Response(false, e.getMessage()));
        }

        return ResponseEntity.ok().body(new Response(true, "处理成功", user));
    }



    /**
     * 获取修改用户的界面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping(value = "edit/{id}")
    public ModelAndView modifyForm(@PathVariable("id") Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return new ModelAndView("users/edit", "userModel", model);
    }



}
